import datetime
import json

from django.http import JsonResponse, HttpResponse
from django.shortcuts import render
from django.views import View

from .models import BookInfo
from .serializer import BookInfoSerializers


class BooksAPIVIew(View):
    """
       查询所有图书、增加图书
    """

    def get(self, request):
        """
        查询所有图书
        路由：GET /books/
        """
        queryset = BookInfo.objects.all()
        # book_list = []
        # for book in queryset:
        #     book_list.append({
        #         'id': book.id,
        #         'btitle': book.btitle,
        #         'bpub_date': book.bpub_date,
        #         'bread': book.bread,
        #         'bcomment': book.bcomment,
        #         # 'image': book.image.url if book.image else ''
        #     })
        # return JsonResponse(book_list, safe=False)
        serializer = BookInfoSerializers(queryset, many=True)  # 序列化
        return JsonResponse(serializer.data, safe=False)

    def post(self, request):
        """
        新增图书
        路由：POST /books/
        """
        json_bytes = request.body
        json_str = json_bytes.decode()
        book_dict = json.loads(json_str)

        # 验证参数
        ser = BookInfoSerializers(data=book_dict)
        # 验证方法，自动跳到序列化器定义的选项参数进行验证
        ser.is_valid(raise_exception=True)  # 自动抛出异常
        print(ser.validated_data)  # 验证后的数据存为字典形式

        # book = BookInfo.objects.create(
        #     btitle=book_dict.get('btitle'),
        #     bpub_date=datetime.strptime(book_dict.get('bpub_date'), '%Y-%m-%d').date()
        # )
        #
        # return JsonResponse({
        #     'id': book.id,
        #     'btitle': book.btitle,
        #     'bpub_date': book.bpub_date,
        #     'bread': book.bread,
        #     'bcomment': book.bcomment,
        #     'image': book.image.url if book.image else ''
        # }, status=201)
        return JsonResponse(ser.errors)


class BookAPIView(View):
    def get(self, request, pk):
        """
        获取单个图书信息
        路由： GET  /books/<pk>/
        """
        try:
            book = BookInfo.objects.get(pk=pk)
        except BookInfo.DoesNotExist:
            return HttpResponse(status=404)

        return JsonResponse({
            'id': book.id,
            'btitle': book.btitle,
            'bpub_date': book.bpub_date,
            'bread': book.bread,
            'bcomment': book.bcomment,
            'image': book.image.url if book.image else ''
        })

    def put(self, request, pk):
        """
        修改图书信息
        路由： PUT  /books/<pk>
        """
        try:
            book = BookInfo.objects.get(pk=pk)
        except BookInfo.DoesNotExist:
            return HttpResponse(status=404)

        json_bytes = request.body
        json_str = json_bytes.decode()
        book_dict = json.loads(json_str)

        # 此处详细的校验参数省略

        book.btitle = book_dict.get('btitle')
        book.bpub_date = datetime.strptime(book_dict.get('bpub_date'), '%Y-%m-%d').date()
        book.save()

        return JsonResponse({
            'id': book.id,
            'btitle': book.btitle,
            'bpub_date': book.bpub_date,
            'bread': book.bread,
            'bcomment': book.bcomment,
            'image': book.image.url if book.image else ''
        })

    def delete(self, request, pk):
        """
        删除图书
        路由： DELETE /books/<pk>/
        """
        try:
            book = BookInfo.objects.get(pk=pk)
        except BookInfo.DoesNotExist:
            return HttpResponse(status=404)

        book.delete()

        return HttpResponse(status=204)